<?php
/**
 * @Author: rocky
 * @Copyright: 广州拓冠科技 <http://my8m.com>
 * Date: 2019/9/6
 * Time: 14:57
 */


namespace app\common\tools;


use think\facade\Config;

/**
 * Class Redis
 * @return $this
 * @package app\common\tools
 */
class Redis
{

    protected $config = [];
    protected static $redis = null;
    private function __construct($options = [])
    {
        if (!extension_loaded('redis')) {
            throw new \Exception('redis扩展未安装');
        }
        self::$redis = new \Redis();
        $config = [
            'host' => Config::get('redis.host', '127.0.0.1'),
            'port' => Config::get('redis.port', '6379'),
            'timeout' => Config::get('redis.timeout', 60),
            'password' => Config::get('redis.password', ''),
            'select' => Config::get('redis.database', '0'),
            'persistent' => Config::get('redis.persistent', false)
        ];
        $this->config = array_merge($config, $options);
        if ($this->config['persistent']) {
            self::$redis->pconnect($this->config['host'], $this->config['port'], $this->config['timeout']);
        } else {
            self::$redis->connect($this->config['host'], $this->config['port'], $this->config['timeout']);
        }
        if ('' != $this->config['password']) {
            self::$redis->auth($this->config['password']);
        }
        if (0 != $this->config['select']) {
            self::$redis->select($this->config['select']);
        }
    }

    /**
     * 返回redis对象
     * @Author: rocky
     * 2019/12/16 9:39
     * @return \Redis
     * @throws \Exception
     */
    public static function getRedis($options = []){
        if (is_null(self::$redis)) {
            new self($options);
        }
        return self::$redis;
    }
}